﻿using Microsoft.EntityFrameworkCore;
using System.Diagnostics.Eventing.Reader;
using TencentCloud.Ame.V20190916.Models;
using TencentCloud.Batch.V20170312.Models;
using TencentCloud.Ocr.V20181119.Models;
using TencentCloud.Weilingwith.V20230427.Models;
using ZenSystemService.Api.Common;
using ZenSystemService.Api.Data;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.Entities;
using static System.Runtime.InteropServices.JavaScript.JSType;


namespace ZenSystemService.Api.Services
{
    public class CourseService
    {
        private readonly ApplicationDbContext _context;

        public CourseService(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取课程类型信息列表
        /// </summary>
        /// <param name="InstitutionId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<CourseType>> GetCourseTypeListAsync(int InstitutionId)
        {
            return await _context.CourseTypes.Where(item => item.Enabled == "1"&&item.InstitutionId==InstitutionId).ToListAsync();
        }


        /// <summary>
        /// 获取课程类型信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<CourseType> GetCourseTypeByIdAsync(int id)
        {
            try
            {
                return await _context.CourseTypes.FindAsync(id);
            }
            catch (Exception ex)
            {
                return null;
            }
        }



        public async Task<IEnumerable<Course>> GetAllCourseAsync()
        {
            return await _context.Courses.Where(item => item.Enabled == "1").OrderBy(item=>item.StartTime).ToListAsync();
        }



        /// <summary>
        /// 查询课程信息
        /// </summary>
        /// <param name="CoachId"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public async Task<IEnumerable<Course>> GetCoursesListAsync(int? InstitutionId, int? CoachId, DateTime? date)
        {
            IEnumerable<Course> list = await _context.Courses.Where(item => item.Enabled == "1").OrderBy(item => item.CourseStatus).ThenBy(item => item.StartTime).ToListAsync();
            if (list != null && date.HasValue)
            {
                list = list.Where(item => item.StartTime.Date == date.Value.Date).ToList();
            }
            if (list != null && InstitutionId.HasValue && InstitutionId.Value > 0)
            {
                list = list.Where(item => item.InstitutionId == InstitutionId.Value).ToList();
            }
            if (list != null && CoachId.HasValue && CoachId.Value > 0)
            {
                list = list.Where(item => item.CoachId == CoachId.Value|| item.SubstituteCoachId== CoachId.Value).ToList();
            }
            return list;
        }

        public async Task<IEnumerable<Course>> GetCoursesListByTraineeAsync(int[] TraineIdArr, DateTime? date)
        {
            IEnumerable<Course> list = await _context.Courses.Where(item => item.Enabled == "1").OrderBy(item => item.CourseStatus).ThenBy(item => item.StartTime).ToListAsync();
            if (list != null && date.HasValue)
            {
                list = list.Where(item => item.StartTime.Date == date.Value.Date).ToList();
            }
            List<int> CourseIdList = new List<int>();
            for (int i = 0; i < TraineIdArr.Length; i++)
            {
                List<CourseTrainee> TraineCourseTraineeList = await this.GetCourseTraineeListByTraineeId(TraineIdArr[i]);
                if (TraineCourseTraineeList != null)
                {
                    for (int j = 0; j < TraineCourseTraineeList.Count; j++)
                    {
                        CourseIdList.Add(TraineCourseTraineeList[j].CourseId);
                    }
                }
            }

            list = list.Where(item => CourseIdList.Contains(item.CourseId)).ToList();
            return list;
        }


        public async Task<IEnumerable<Course>> GetCoursesListByTraineeAsync(int[] TraineIdArr, DateTime _startDate, DateTime _endDate)
        {
            DateTime StartDate = Convert.ToDateTime(_startDate.ToString("yyyy-MM-dd") + " 0:00:00");
            DateTime EndDate = Convert.ToDateTime(_endDate.ToString("yyyy-MM-dd") + " 23:59:59");
            IEnumerable<Course> list = await _context.Courses.Where(item => item.Enabled == "1" && item.StartTime >= StartDate && item.EndTime <= EndDate).OrderBy(item => item.CourseStatus).ThenBy(item => item.StartTime).ToListAsync();
            
            List<int> CourseIdList=new List<int>();
            for (int i = 0; i < TraineIdArr.Length; i++)
            {
                List<CourseTrainee> TraineCourseTraineeList = await this.GetCourseTraineeListByTraineeId(TraineIdArr[i]);
                if (TraineCourseTraineeList != null)
                {
                    for (int j = 0; j < TraineCourseTraineeList.Count; j++)
                    {
                        CourseIdList.Add(TraineCourseTraineeList[j].CourseId);
                    }
                }
            }

            list = list.Where(item => CourseIdList.Contains(item.CourseId)).ToList();
            return list;
        }

        /// <summary>
        /// 查询课程信息
        /// </summary>
        /// <param name="InstitutionId"></param>
        /// <param name="CoachId"></param>
        /// <param name="StartDate"></param>
        /// <param name="EndDate"></param>
        /// <returns></returns>
        public async Task<IEnumerable<Course>> GetCoursesListAsync(int? InstitutionId, int? CoachId, DateTime _startDate, DateTime _endDate)
        {
            DateTime StartDate = Convert.ToDateTime(_startDate.ToString("yyyy-MM-dd") + " 0:00:00");
            DateTime EndDate = Convert.ToDateTime(_endDate.ToString("yyyy-MM-dd") + " 23:59:59");
            IEnumerable<Course> list = await _context.Courses.Where(item => item.Enabled == "1"&& item.StartTime>= StartDate&& item.EndTime<= EndDate).OrderBy(item => item.CourseStatus).ThenBy(item => item.StartTime).ToListAsync();
            if (list != null && InstitutionId.HasValue && InstitutionId.Value > 0)
            {
                list = list.Where(item => item.InstitutionId == InstitutionId.Value).ToList();
            }
            if (list != null && CoachId.HasValue && CoachId.Value > 0)
            {
                list = list.Where(item => item.CoachId == CoachId.Value|| item.SubstituteCoachId == CoachId.Value).ToList();
            }
            return list;
        }

        /// <summary>
        /// 获取未完成课程信息
        /// </summary>
        /// <param name="InstitutionId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<Course>> GetNotFinishedCourseList(int? InstitutionId)
        {
            IEnumerable<Course> list = await _context.Courses.Where(item => item.Enabled == "1" && item.InstitutionId >= InstitutionId && (item.CourseStatus== (int)CourseStatus.NotStarted|| item.CourseStatus == (int)CourseStatus.Starting)).OrderBy(item => item.CourseStatus).ThenBy(item => item.StartTime).ToListAsync();
            return list;
        }


        /// <summary>
        /// 添加课程
        /// </summary>
        /// <param name="course"></param>
        /// <returns></returns>
        public bool CreateCourseAsync(ref Course course)
        {
            _context.Courses.Add(course);
            int count = _context.SaveChanges();
            return count > 0 ? true : false;
        }

        public async Task<bool> UpdateCourseAsync(Course course)
        {
            _context.Entry(course).State = EntityState.Modified;
            int count = await _context.SaveChangesAsync();
            return count > 0 ? true : false;
        }


        public async Task<bool> DeleteCourseAsync(int id)
        {
            var _course = await _context.Courses.FindAsync(id);
            if (_course != null)
            {
                _context.Courses.Remove(_course);
                int count = await _context.SaveChangesAsync();
                return count > 0 ? true : false;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取课程信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Course> GetCourseByIdAsync(int id)
        {
            return await _context.Courses.FindAsync(id);
        }

        /// <summary>
        /// 根据课程ID 得到课程学员信息
        /// </summary>
        /// <param name="CourseId"></param>
        /// <returns></returns>
        public List<User> GetCourseTraineeList(int CourseId)
        {
            var list = _context.CourseTrainees.Where(item=>item.CourseId== CourseId&& item.Enabled=="1").ToList();

            if (list != null && list.Count > 0)
            {
                int[] Arr=new int[list.Count];
                for (int i = 0; i < list.Count; i++)
                {
                    Arr[i] = list[i].TraineeId;
                }
               return  _context.Users.Where(item => Arr.Contains(item.UserId)).ToList();
            }
            else
            {
                return null;
            }
           
        }


        /// <summary>
        /// 添加课程学员信息
        /// </summary>
        /// <param name="_courseTrainee"></param>
        /// <returns></returns>
        public bool CreateCourseTrainee(ref CourseTrainee _courseTrainee)
        {
            _context.CourseTrainees.Add(_courseTrainee);
            int count = _context.SaveChanges();
            return count > 0 ? true : false;
        }

        /// <summary>
        /// 获取课程学员信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<CourseTrainee> GetCourseTraineeByIdAsync(int id)
        {
            return await _context.CourseTrainees.FindAsync(id);
        }

        /// <summary>
        /// 根据课程ID 学员ID 得到课程学员信息
        /// </summary>
        /// <param name="CourseId"></param>
        /// <param name="TraineeId"></param>
        /// <returns></returns>
        public async Task<CourseTrainee> GetCourseTraineeAsync(int CourseId, int TraineeId)
        {
            try
            {
                var courseTrainee = await _context.CourseTrainees.SingleOrDefaultAsync(u => u.CourseId == CourseId && u.TraineeId == TraineeId && u.Enabled == "1");
                return courseTrainee;
            }
            catch
            {
                return null;
            }
        }


       /// <summary>
       ///  根据课程ID 获取课程学员信息
       /// </summary>
       /// <param name="CourseId"></param>
       /// <returns></returns>
        public async Task<List<CourseTrainee>> GetCourseTraineeListByCourseId(int CourseId)
        {
            return await _context.CourseTrainees.Where(item => item.CourseId == CourseId && item.Enabled == "1").ToListAsync();
        }

        /// <summary>
        /// 根据学员ID 获取课程学员信息
        /// </summary>
        /// <param name="TraineeId"></param>
        /// <returns></returns>
        public async Task<List<CourseTrainee>> GetCourseTraineeListByTraineeId(int TraineeId)
        {
            return await _context.CourseTrainees.Where(item => item.TraineeId == TraineeId && item.Enabled == "1").ToListAsync();
        }


        public async Task<bool> AddCancelReservationCourse(CancelReservationCourse _cancelReservationCourse)
        {
            _context.CancelReservationCourses.Add(_cancelReservationCourse);
            int count = await _context.SaveChangesAsync();
            return count > 0 ? true : false;
        }

        /// <summary>
        /// 更新课程学员信息
        /// </summary>
        /// <param name="_courseTrainee"></param>
        /// <returns></returns>
        public async Task<bool> UpdateCourseTraineeAsync(CourseTrainee _courseTrainee)
        {
            _context.Entry(_courseTrainee).State = EntityState.Modified;
            int count = await _context.SaveChangesAsync();
            return count > 0 ? true : false;
        }


        /// <summary>
        /// 获取训练项信息列表
        /// </summary>
        /// <param name="InstitutionId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<TrainingItem>> GetTrainingItemListAsync(int InstitutionId)
        {
            return await _context.TrainingItems.Where(item => item.Enabled == "1" && item.InstitutionId == InstitutionId).ToListAsync();
        }


        public async Task<TrainingItem> GetTrainingItemInfoById(int id)
        {
            return await _context.TrainingItems.FindAsync(id);
        }


        /// <summary>
        /// 添加课程训练项信息
        /// </summary>
        /// <param name="_courseTrainingItem"></param>
        /// <returns></returns>
        public bool CreateCourseTrainingItem(ref CourseTrainingItem _courseTrainingItem)
        {
            _context.CourseTrainingItems.Add(_courseTrainingItem);
            int count = _context.SaveChanges();
            return count > 0 ? true : false;
        }


        /// <summary>
        /// 删除课程训练项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteCourseTrainingItem(int id)
        {
            var courseTrainingItem = await _context.CourseTrainingItems.FindAsync(id);
            if (courseTrainingItem != null)
            {
                _context.CourseTrainingItems.Remove(courseTrainingItem);
                int count = await _context.SaveChangesAsync();
                return count > 0 ? true : false;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 获取课程训练项信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<CourseTrainingItem> GetCourseTrainingItemByIdAsync(int id)
        {
            return await _context.CourseTrainingItems.FindAsync(id);
        }

        /// <summary>
        /// 根据课程ID 获取课程训练项信息列表
        /// </summary>
        /// <param name="CourseId"></param>
        /// <returns></returns>
        public async Task<List<CourseTrainingItem>> GetCourseTrainingItemListByCourseIdAsync(int CourseId)
        {
            return await _context.CourseTrainingItems.Where(item => item.CourseId == CourseId).ToListAsync();
        }



        /// <summary>
        /// 添加代课记录
        /// </summary>
        /// <param name="substituteCourseRecord"></param>
        /// <returns></returns>
        public async Task<bool> AddSubstituteCourseRecord(SubstituteCourseRecord substituteCourseRecord)
        {
            _context.SubstituteCourseRecords.Add(substituteCourseRecord);
            int count = await _context.SaveChangesAsync();
            return count > 0 ? true : false;
        }
    }
}
